import * as Cesium from 'cesium';
import gisTools from '../GisTools';
import mouseHelper from '../MouseHelper';
//当前类使用的全局的viewer
let cviewer: any = {};
//当前类的事件句柄
let handler: any = {};

/**
 * 添加、清除、测试过
 */
class MeasurePolyline {
  _drawingGraphic: any;
  _drawingPositions: any;
  _drawingPointEntities:any;
  isDrawingEnd: any;
  constructor(viewer: any) {
    //绘制中的graphic-主要绘制线   --- 脏数据
    this._drawingGraphic = null;
    //绘制中的geometry-主要绘制线  -数据类型 Cartesian3  ---脏数据
    this._drawingPositions = [];
    //绘制过程中活动的点 --脏数据
    this._drawingPointEntities=[];
    //是否绘制结束
    this.isDrawingEnd = false;
    cviewer = viewer;
    handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  }

  /**
   * 开始绘制
   * @param bNeed  true | false  表示绘制动作是否是连续性的，即绘制完一个不结束，默认false
   * @param options  {
   *   "Polyline":{ "stroken":"线颜色","width":"线宽度" }
   *      "popOffset":{x:400,y:0}
   * }
   */
  startMeasure(options: any={}) {
    this.clearDrawGraphic();
    let _this = this;
    let { popOffset } = options;
    //创建初始化
    mouseHelper.createHelper({ x:-500,y:-500 }, '',popOffset);
    //左键事件-添加真实的点
    handler.setInputAction(function(evt: any) {
      let car3 = gisTools.getCar3Position(cviewer,evt.position);
      if(car3){
        if(_this._drawingPositions.length===0){
          _this._drawingPositions.push(car3.clone());
        }
        _this._drawingPositions.push(car3);
        _this.createPoint(car3.clone());
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    //鼠标移动事件-添加虚拟的点
    handler.setInputAction(function(evt: any) {
      let car3 = gisTools.getCar3Position(cviewer,evt.endPosition);
      //未点击左键的时候的提示
       if(_this._drawingPositions.length===0){
         mouseHelper.updateHelper(evt.endPosition, '左键点击开始',popOffset);
       }
        //线最少两个点-一个点的时候提示
        if (_this._drawingPositions.length > 0  && _this._drawingPositions.length < 2  ) {
          mouseHelper.updateHelper(evt.endPosition, '左键点击继续绘制',popOffset);
        }
        //线的点数大于等于2的时候的提示
        if (_this._drawingPositions.length >= 2) {
          mouseHelper.updateHelper(evt.endPosition, '左键点击继续绘制，右键点击结束绘制',popOffset);
        }
        //点的数量大于等于1的时候开始画线
        if(_this._drawingPositions.length>0){
          _this._drawingPositions.pop();
          _this._drawingPositions.push(car3);
          if (!_this._drawingGraphic) {
            let { Polyline } = options;
            _this._drawingGraphic = _this.createPolyline(Polyline);
          }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    //鼠标右键事件
    handler.setInputAction(function(evt: any) {
      let car3 = gisTools.getCar3Position(cviewer,evt.position);
      if(_this._drawingPositions.length>1){
        //鼠标动态绘制过程的点+1
        _this._drawingPositions.push(car3);
        _this.createPoint(car3.clone());
        //如果是一次绘制，绘制结束完，清除事件
        _this.isDrawingEnd = true;
        _this.endDrawing();
      }
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  }
  /**
   *结束绘制的事件
   */
  endDrawing() {
    if(handler){
      handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    mouseHelper.removeHelper();
    return true;
  }

  /**
   * 清除绘制的Graphic
   */
  clearDrawGraphic() {
    this.endDrawing();
    if(this._drawingPointEntities.length>0){
      this._drawingPointEntities.forEach((item:any)=>{
        cviewer.entities.remove(item)
      })
    }
    this.isDrawingEnd=false;
    this._drawingGraphic = null;
    this._drawingPositions = [];
    return true;
  }

  createPoint(cartesian:any) {
    let $this = this;
    let point:any=null;
    let distance:any=this.getSpaceDistance(this._drawingPositions);
    let regex = /[\d.]+/g;
    let matches = distance.match(regex);
    matches=Number(matches[0]);
    if(matches>0){
       point = cviewer.entities.add({
        position: cartesian,
        point: {
          pixelSize: 10,
          color: Cesium.Color.YELLOW,
        },
        label: {
          text: distance,
          font: '18px sans-serif',
          style : Cesium.LabelStyle.FILL,
          outlineWidth : 1,
          fillColor:Cesium.Color.YELLOW,
          showBackground:false,
          backgroundColor:Cesium.Color.ORANGE.withAlpha(0.6),
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
          pixelOffset: new Cesium.Cartesian2(5.0,-20.0),
        }
      });
    }else{
      point = cviewer.entities.add({
        position: cartesian,
        point: {
          pixelSize: 10,
          color: Cesium.Color.YELLOW,
        }
      });
    }

    $this._drawingPointEntities.push(point);
    return point;
  }



  /**
   * 创建线
   * @param positionArr-绘制过程中的动态的线
   * @param style
   */
  createPolyline(style: any) {
    if(!style){
      style={
        stroken:"#DC143C",
        width:3
      }
    }
    style['stroken'] = style?.stroken ?? '#DC143C';
    style['width'] = style?.width ?? 3;
    let _this = this;
    var polyline = cviewer.entities.add({
      polyline: {
        id: 'area_search_draw_graphic_polyline' + new Date().getTime(),
        //使用cesium的peoperty
        positions: new Cesium.CallbackProperty(function() {
          return _this._drawingPositions;
        }, false),
        show: true,
        material: Cesium.Color.fromCssColorString(style['stroken']),
        width: style['width'],
        clampToGround: true,
      },
    });
    return polyline;
  }


  getSpaceDistance(positions:any) {
    let distance:any = 0;
    var $this=this;
    for (var i = 0; i < positions.length - 1; i++) {
      var point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
      var point2cartographic = Cesium.Cartographic.fromCartesian(positions[i + 1]);
      /**根据经纬度计算出距离**/
      var geodesic = new Cesium.EllipsoidGeodesic();
      geodesic.setEndPoints(point1cartographic, point2cartographic);
      var s = geodesic.surfaceDistance;
      //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
      //返回两点之间的距离
      s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
      distance = distance + s;
    }
    return distance.toFixed(2)>1000 ? (distance/1000).toFixed(2)+"公里" : distance.toFixed(2)+"米";
  }


}

export default MeasurePolyline;



